package websocket

import (
	"encoding/json"
	"fmt"

	"log"

	"os/exec"
	"runtime"
	"strings"
	"time"

	"tuiwen-go/internal/api"
	"tuiwen-go/internal/db"
)

func taskRegenerateAllHandler(c *Client, data json.RawMessage) {
	log.Printf("Client %s: Handling Regenerate All Task, Data: %s", c.ID, string(data))

	taskAutoSceneHandler(c, data)
	taskAudioByComfyuiHandler(c, data)
	taskImgByComfyuiHandler(c, data)
	taskDraftHandler(c, data)
	sendMessage(c, api.WxJSONResponse{Code: 0, Msg: "Regenerate All task received and acknowledged"})
}

// taskNormalHandler 处理类型为 0 的消息。
func taskNormalHandler(c *Client, data json.RawMessage) {
	log.Printf("Client %s: Handling Normal Task, Data: %s", c.ID, string(data))
	// TODO: 实现普通任务的实际逻辑
	sendMessage(c, api.WxJSONResponse{Code: 0, Msg: "Normal task received and acknowledged"})
}

// taskAddHandler 处理类型为 1 的消息。
func taskAddHandler(c *Client, data json.RawMessage) {
	log.Printf("Client %s: Handling Add Task, Data: %s", c.ID, string(data))

	var taskData struct {
		Name             string   `json:"name"`
		TextContent      string   `json:"textContent"`
		Status           int      `json:"status"`
		TextContentSplit []string `json:"textContentSplit"` // 假设这由客户端提供
	}

	if err := json.Unmarshal(data, &taskData); err != nil {
		log.Printf("Client %s: Error unmarshalling add task data: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "Invalid add task data format"})
		return
	}

	var segmentedText []string
	if len(taskData.TextContentSplit) > 0 {
		segmentedText = taskData.TextContentSplit // 如果可用，使用客户端提供的分割结果（不太理想）
	} else if taskData.TextContent != "" {
		// 作为回退/占位符，按常见分隔符简单分割
		segmentedText = strings.FieldsFunc(taskData.TextContent, func(r rune) bool {
			return r == '\n' || r == '。' || r == '！' || r == '？' // 示例分隔符
		})
		// 去除每个分段的空白字符
		for i := range segmentedText {
			segmentedText[i] = strings.TrimSpace(segmentedText[i])
		}
		// 过滤掉空分段
		var filteredSegments []string
		for _, segment := range segmentedText {
			if segment != "" {
				filteredSegments = append(filteredSegments, segment)
			}
		}
		segmentedText = filteredSegments
	} else {
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "Text content or split content is empty"})
		return
	}

	// 插入到项目表中
	projectResult, err := db.Exec("INSERT INTO project (name, textContent, createTime, status) VALUES (?, ?, ?, ?)",
		taskData.Name,
		taskData.TextContent,
		time.Now(),
		taskData.Status,
	)
	if err != nil {
		log.Printf("Client %s: Error inserting project into DB: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "Failed to add project to database"})
		return
	}

	projectID, err := projectResult.LastInsertId()
	if err != nil {
		log.Printf("Client %s: Error getting last insert ID for project: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "Failed to get new project ID"})
		return
	}

	sendMessage(c, api.WxJSONResponse{Code: 1, Msg: "项目入库成功", Data: map[string]interface{}{"projectId": projectID}})

	// 准备插入文本表的数据
	var textValues []interface{}
	textQuery := "INSERT INTO text (project_id, content) VALUES "
	valueStrings := []string{}
	for _, content := range segmentedText {

		// 每个文本块的关键词分割占位符
		// 这需要一个 Go 分割库
		// 目前，我们只是将块本身存储为内容，并将单词的 JSON 数组作为分割结果
		// 正确的实现应该在这里调用一个分割函数

		valueStrings = append(valueStrings, "(?,?)")
		textValues = append(textValues, projectID, content)
	}

	textQuery += strings.Join(valueStrings, ",")

	// 在事务中插入到文本表以确保安全
	tx, err := db.DB.Begin()
	if err != nil {
		log.Printf("Client %s: Error starting transaction for text insertion: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "Failed to start transaction for text insertion"})
		return
	}

	_, err = tx.Exec(textQuery, textValues...)
	if err != nil {
		tx.Rollback()
		log.Printf("Client %s: Error inserting text into DB: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "Failed to add text content to database"})
		return
	}

	err = tx.Commit()
	if err != nil {
		log.Printf("Client %s: Error committing transaction for text insertion: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "Failed to commit text insertion transaction"})
		return
	}

	sendMessage(c, api.WxJSONResponse{Code: 1, Msg: "文案及分词存入数据库成功"})
}

// cancelAutoClosePCHandler 处理类型为 998 的消息。
func cancelAutoClosePCHandler(c *Client, data json.RawMessage) {
	log.Printf("Client %s: Handling Cancel Auto Close PC, Data: %s", c.ID, string(data))

	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "shutdown"
		args = []string{"-a"} // 中止关机
	case "darwin":
		cmd = "shutdown"
		args = []string{"-c"} // 取消关机
	case "linux":
		cmd = "shutdown"
		args = []string{"-c"} // 取消关机
	default:
		log.Printf("Client %s: Cancel auto-close PC not supported on this OS: %s", c.ID, runtime.GOOS)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: fmt.Sprintf("取消自动关机不支持当前操作系统: %s", runtime.GOOS)})
		return
	}

	// 执行取消关机命令
	command := exec.Command(cmd, args...)
	err := command.Run() // 使用 Run()，因为这是一个短期命令
	if err != nil {
		log.Printf("Client %s: Error executing cancel auto-close command '%s %v': %v", c.ID, cmd, args, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: fmt.Sprintf("执行取消自动关机命令失败: %v", err)})
		return
	}

	log.Printf("Client %s: Cancel auto-close command '%s %v' executed successfully", c.ID, cmd, args)
	sendMessage(c, api.WxJSONResponse{Code: 0, Msg: "已取消自动关机"})
}

// utils.SplitText 的占位符，如果它很复杂或涉及外部库
// 目前，假设它是一个简单的字符串分割或类似操作，可以内联或轻松添加
// 如果 utils.SplitText 很重要，应该在 utils 包中实现
func splitText(text string) []string {
	// 这是一个占位符。请替换为实际的文本分割逻辑
	// 例如，使用 strings.Split 或更复杂的分词器
	log.Printf("Splitting text (placeholder): %s", text)
	return strings.Split(text, ",") // 示例：按逗号分割
}
